<?php
namespace Ns;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface  as Request;
use Psr\Http\Message\ResponseInterface  as Response;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
 
class RequestTimeMiddleware implements MiddlewareInterface
{
    public function process(Request $request, RequestHandler $handler): Response
    {
        $start = microtime(true);
        $request = $request->withAttribute('foo', 'bar');
        // 处理请求
        $response = $handler->handle($request);
         
        // 计算请求时间
        $end = microtime(true);
        $time = $end - $start;
        //  var_dump('time',$time);
         print_r(  $time."\n");
        // 将请求时间添加到响应头中
        $response = $response->withHeader('X-Request-Time', $time);
         
        return $response;
    }
}